/*
 * Copyright 2009 Lukasz Wozniak
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package pl.lwozniak.http;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Properties;

/**
 * Base class providing ways of instantiating {@link HttpConnectorFactory}. Uses
 * property file to read configured class of factory and optionaly passes this
 * property file to the factory for aditional configuration. Ideally provider of
 * alternative {@link HttpConnectorFactory} provides
 * <code>yajba_http_factory.properties</code> on classpath (in root of his JAR)
 * and his factory is instantiated and returned to the user. Changing JAR
 * results in other factory being used without any change needed in client code.
 * 
 * @author Lukasz Wozniak
 * 
 */
public abstract class AbstractHttpConnectorFactory implements
		HttpConnectorFactory {

	public static final String DEFAULT_FACTORY_PROPERTIES = "yajba_http_factory.properties";

	public static final String FACTORY_CLASS_NAME_PROPERTY_NAME = "yajba.factory.classname";

	public static final String DEFAULT_FACTORY_CLASS_NAME = "pl.lwozniak.http.DefaultHttpConnectorFactory";

	private static final Class<?>[] PROPS_PARAMS_ARRAY = new Class<?>[] { Properties.class };

	/**
	 * Uses default provided factory or the one configured in default property
	 * file.
	 * 
	 * @return instance of {@link HttpConnectorFactory}
	 */
	public static HttpConnectorFactory newInstance() {
		Properties props = new Properties();
		InputStream is = AbstractHttpConnectorFactory.class.getClassLoader()
				.getResourceAsStream(DEFAULT_FACTORY_PROPERTIES);
		if (is == null) {
			props.setProperty(FACTORY_CLASS_NAME_PROPERTY_NAME,
					DEFAULT_FACTORY_CLASS_NAME);
		} else {
			try {
				props.load(is);
			} catch (IOException e) {
				// shouldnt happen but if...
				throw new RuntimeException(
						"Fatal error reading factory configuration");
			}
		}
		return newInstance(props);

	}

	/**
	 * Uses provided properties to create factory.
	 * 
	 * @param props
	 *            properties configuring factory. property
	 *            {@link AbstractHttpConnectorFactory#FACTORY_CLASS_NAME_PROPERTY_NAME}
	 *            is mandatory
	 * @return instance of {@link HttpConnectorFactory}
	 */
	public static HttpConnectorFactory newInstance(Properties props) {
		String classname = props.getProperty(FACTORY_CLASS_NAME_PROPERTY_NAME);
		if (classname != null) {
			try {
				Class<?> clazz = Class.forName(classname);
				if (HttpConnectorFactory.class.isAssignableFrom(clazz)) {
					try {
						Constructor<?> c = clazz
								.getConstructor(PROPS_PARAMS_ARRAY);
						return (HttpConnectorFactory) c
								.newInstance(new Object[] { props });
					} catch (Exception e) {
						// ignore doesn't matter
					} 
					// fallback to default constructor
					return (HttpConnectorFactory) clazz.newInstance();
				} else {
					throw new IllegalArgumentException(classname
							+ " does not implement "
							+ HttpConnectorFactory.class.getName());
				}
			} catch (ClassNotFoundException e) {
				throw new IllegalArgumentException(e);
			} catch (InstantiationException e) {
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		} else {
			throw new IllegalArgumentException(
					"Invalid factory configuration. "
							+ FACTORY_CLASS_NAME_PROPERTY_NAME);
		}
	}

}
